package main

import (
	"fmt"
	"time"
)

/**
n个协程交替打印数字
 */
func main()  {
	num := 3
	chs := make([]chan int, num)
	for i:=0; i<num; i++ {
		chs[i] = make(chan int)
	}
	finish := make(chan struct{})
	for i := 0; i < num; i++ {
		go nprint(i, chs[i], chs[(i+1)%num], finish)
	}
	chs[0]<-1
	time.Sleep(10 * time.Second)
	finish<-struct{}{}
}

func nprint(id int, pre <-chan int, next chan<- int, finish <-chan struct{}) {
	for {
		select {
		case num := <-pre:
			time.Sleep(time.Second)
			fmt.Printf("goroutine:%d print:%d\n", id, num)
			num++
			next<-num
		case <-finish:
			return
		}
	}
}
